<?php
namespace models;
class classes
{

    public $checkRules = [
        'name' => ['string', '2,10', '班级名称应该在2-10个字符'],
    ];

// 新增班级
    public function add($nameArray)
    {
        foreach ($nameArray as $key => $name) {
            db('classes')->add(['name' => $name]);
        }

    }

// 取已分配到教师的班级
    public function getAssignedClasses()
    {

        $list = db('classes')->join(' as a left join tb_users as b on a.teacher_id=b.id')
            ->where('a.teacher_id > ?', 0)
            ->order('a.name')
            ->fetchAll('a.name as classname,a.id,b.realname as username');

        $r = [];
        foreach ($list as $key => $v) {
            //把查询结果按教师名称重组
            $r[$v['username']][] = [$v['id'], $v['classname']];
        }
        return $r;
    }

// 取所有未分配的班级
    public function getFreeClasses()
    {
        return db('classes')->where('teacher_id=?', 0)->order('name')->fetchAll();

    }

// 分配一个或多个班级给老师
    public function assignClass($id, $teacher_id)
    {
        foreach ($id as $key => $classID) {
            db('classes')->where('id=?', $classID)->update(['teacher_id' => $teacher_id]);
        }
    }

// 取消分配(单个班级)
    public function cancelAssignClass($id)
    {
        return db('classes')->where('id=?', $id)->update(['teacher_id' => 0]);
    }

// 批量删除选中的班级
    public function delByID()
    {
        $ids = $_POST['id'];
        foreach ($ids as $id) {
            db('classes')->where('id=?', $id)->delete();
        }

    }

// 取某教师的任教班级
    public function getClassByTeacher($tid)
    {
        return db('classes')->where('teacher_id = ?', $tid)->order('name')->fetchAll();

    }

}
